import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/cupertino.dart';

import '../../db/entity/AttributeBean.dart';
import '../../db/entity/ProductAttrBean.dart';
import '../../db/entity/ProductBean.dart';
import '../../main.dart';
import '../../utils/common.dart';
import '../../widgets/gyy_dropdown_row.dart';
import '../../widgets/gyy_theme.dart';
import 'drop_header_button.dart';
import '../../widgets/page.dart';

///客户下单 - 编辑产品（项目）

class EditBillProductPage extends StatefulWidget {
  final ProductBean product;
  final ValueChanged<Map<String, AttributeBean>> onProductAttrChanged;

  const EditBillProductPage(this.product, this.onProductAttrChanged, {Key? key})
      : super(key: key);

  @override
  State<EditBillProductPage> createState() => _EditProductItemState();
}

class _EditProductItemState extends State<EditBillProductPage> {

  var productAttrDao = database.productAttrDao;
  var attributeDao = database.attributeDao;
  late ProductBean product;
  List<AttributeBean> allAttrList = []; //产品扩展的所有属性
  List<AttributeBean> levelOneList = []; //产品扩展的一级属性
  List<AttributeBean> levelTwoList = []; //产品扩展的二级属性
  List<List<AttributeBean>> resultList = []; //二级联动属性
  Map<String, String> allAttrMap = {};

  Map<String, AttributeBean> allInputAttrMap = {};
  bool isOpen = true;

  //产品自带的属性
  AttributeBean buildAttrBean(String code, String name, String value) {
    AttributeBean bean =  AttributeBean.value(
      attributeCode : code,
      attributeName: name,
      attributeValue : value,
      createTime : DateTime.now(),
      updateTime :DateTime.now(),
    );
    return bean;
  }


  findProductAttr() async {
    //产品默认属性
    doDefaultAttr();
    //产品扩展属性
    List<ProductAttrBean> productAttr =
        await productAttrDao.findByProductId(product.id!);
    if (productAttr.isEmpty) {
      return;
    }
    var codes = productAttr.map((e) => e.attributeCode).toList();
    //产品属性
    allAttrList = await attributeDao.findInCodesList(codes);
    //组装二级联动数据
    initAttributeList();
    setState(() {});
  }

  //添加产品自带的属性（同时也排好了顺序）
  doDefaultAttr() {
    //处理产品的默认属性
    allInputAttrMap['unitPrice'] = buildAttrBean('unitPrice', '单价', product.unitPrice.toString());
    allInputAttrMap['number'] = buildAttrBean('number', '数量', product.number.toString());
    allInputAttrMap['typesettingFee'] = buildAttrBean('typesettingFee', '排版费', product.typesettingFee.toString());
    allInputAttrMap['printingFee'] = buildAttrBean('printingFee', '印刷费', product.printingFee.toString());
    allInputAttrMap['subtotalFee'] = buildAttrBean('subtotalFee', '价格小计', product.subtotalFee.toString());
    allInputAttrMap['discount'] =  buildAttrBean('discount', '折扣', product.discount.toString());
    allInputAttrMap['price'] = buildAttrBean('price', '费用小计', product.price.toString());
    allInputAttrMap['remarks'] =  buildAttrBean('remarks', '备注', product.remarks);
    callBack();
  }

  initAttributeList() async {
    for (var element in allAttrList) {
      allAttrMap[element.attributeCode] = element.attributeName;
    }
    //组装二级联动数据
    levelOneList =
        allAttrList.where((element) => element.attributeLevel == 1).toList();
    levelTwoList =
        allAttrList.where((element) => element.attributeLevel == 2).toList();
    for (var one in levelOneList) {
      List<AttributeBean> subList = [];
      for (var two in levelTwoList) {
        if (one.attributeCode == two.parentCode) {
          subList.add(two);
        }
      }
      resultList.add(subList);
    }

  }

  callBack() {
    //回调给父组件
    widget.onProductAttrChanged(allInputAttrMap);
  }

  @override
  void initState() {
    super.initState();
    product = widget.product;
    findProductAttr();
  }

  @override
  Widget build(BuildContext context) {
    final theme = FluentTheme.of(context);
    return Expander(
      initiallyExpanded: isOpen,
      icon: isOpen ? downIcon : upIcon,
      //头部
      header: Text(
        product.productName,
        style: theme.typography.title!.merge(whiteStyle),
      ),
      headerBackgroundColor:
          ButtonState.all(AppTheme.accentColor.withOpacity(0.8)),
      trailing: Text(
        '小计:100￥',
        style: theme.typography.subtitle!.merge(whiteStyle),
      ),
      onStateChanged: (open) => {setState(() => isOpen = open)},
      //内容
      content: Column(
        children: [
          //固定的属性
          Row(children: [
            Expanded(
                child: GyyTextBox(
                    header: '单价',
                    initialValue: product.unitPrice.toString(),
                    onChanged: (changeValue) {
                      allInputAttrMap['unitPrice'] = buildAttrBean('unitPrice', '单价', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '数量',
                    onChanged: (changeValue) {
                      allInputAttrMap['number'] = buildAttrBean('number', '数量', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '排版费',
                    initialValue: product.typesettingFee.toString(),
                    onChanged: (changeValue) {
                      allInputAttrMap['typesettingFee'] = buildAttrBean('typesettingFee', '排版费', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '印刷费',
                    initialValue: product.printingFee.toString(),
                    onChanged: (changeValue) {
                      allInputAttrMap['printingFee'] = buildAttrBean('printingFee', '印刷费', changeValue);
                      callBack();
                    })),
          ]),
          Row(children: [
            Expanded(
                child: GyyTextBox(
                    header: '价格小计',
                    onChanged: (changeValue) {
                      allInputAttrMap['subtotalFee'] = buildAttrBean('subtotalFee', '价格小计', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '折扣',
                    onChanged: (changeValue) {
                      allInputAttrMap['discount'] =  buildAttrBean('discount', '折扣', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '费用小计',
                    onChanged: (changeValue) {
                      allInputAttrMap['price'] = buildAttrBean('price', '费用小计', changeValue);
                      callBack();
                    })),
            Expanded(
                child: GyyTextBox(
                    header: '备注',
                    initialValue: product.remarks,
                    onChanged: (changeValue) {
                      allInputAttrMap['remarks'] =  buildAttrBean('remarks', '备注', changeValue);
                      callBack();
                    })),
          ]),
          sizeBoxV10,
          //扩展的属性
          ...buildWidgets(),
        ],
      ),
    ).padding(const EdgeInsets.only(top: 5));
  }

  buildWidgets() {
    //将属性分组，一组4个
    List<List<AttributeBean>> oneList = splitListBySize(levelOneList, 4);
    // debugPrint('多少行 ==：' + oneList.length.toString());
    List<Row> rows = []; //多少行
    int index = -1; //产品所有属性的角标
    for (var i = 0; i < oneList.length; i++) {
      List<AttributeBean> twoList = oneList[i];
      // debugPrint('多少列 ==：' + twoList.length.toString());
      List<Widget> children = []; //每行的选项
      for (var j = 0; j < twoList.length; j++) {
        index++;
        var e = twoList[j];
        //真实的数据
        if (e.attributeCode.isNotEmpty) {
          var code = e.attributeCode;
          var name = e.attributeName;
          var attribute = allInputAttrMap[e.attributeCode];
          children.add(
            Expanded(
                child: resultList[index].isEmpty
                    ? GyyTextBox(
                        header: name,
                        initialValue: attribute?.attributeValue,
                        onChanged: (changeValue) {
                          e.attributeValue = changeValue;
                          //子code -> 子name
                          allInputAttrMap[code] = e;
                          //回调给父组件
                          widget.onProductAttrChanged(allInputAttrMap);
                        },
                      )
                    : HeaderDropButton(
                        code,
                        name,
                        attribute?.attributeValue ?? '请选择',
                        childrenItems: resultList[index],
                        changed: (check) {
                          e.attributeValue = check.attributeName;
                          //父code -> 子name
                          allInputAttrMap[code] = e;
                          //回调给父组件
                          widget.onProductAttrChanged(allInputAttrMap);
                        },
                      )),
          );
        } else {
          //最后一行 补齐的数据
          children.add(const Expanded(child: sizeBox));
        }
      }
      //所有的行
      rows.add(Row(children: children));
    }
    return rows;
  }
}
